
import React, {useState, useEffect, useMemo} from 'react';
import { WaitUmd, is_empty, Btn, obj_str, loc, PanelFind, Ret, Title, filter_row, show_mt, save_data, useCmd, useHigh, GridTable } from 'sui';
import { reload, load_col } from '../psn/cmd';
import { qbc_psn, db_psn, dt_psn } from './cmd';

const PsnView = ({ tech, cur, hreturn, mod }) => {
    const [main, setMain] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();

    useEffect(() => {
        load_col(setCol);

        reload(null, tech, (v) => {
            if (mod === "qbc") {
                qbc_psn(v, cur, setMain);
            } else if (mod === "db") {
                db_psn(v, cur, setMain);
            } else if (mod === "dt") {
                dt_psn(v, cur, setMain);
            }
        }, cur);
    }, [cur, tech, mod]);

    const getRow = useMemo(() => {
        if (is_empty(col)) {
            return null;
        }

        const lst = col.map(d => d.sn);
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter, col]);

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_864"), key: 'gp', width: 70, frozen: true},
        ];

        col.forEach(d => show_mt(tmp, d, 110));

        return tmp;
    };

    const hout = () => {
        const col = getCol();

        save_data(main, col, loc("l_818"), umd);
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn className="ml-4" hcmd={hout} color="green">{loc("l_298")}</Btn>
            <Ret className="ml-4" hcmd={hreturn}/>
        </div>
    );

    const Left = () => (
        <div className="inline-flex items-center">
            <Title mod={obj_str(tech, "sn")} sub="QBC">{loc("l_818")}</Title>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={<Left/>} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={getCol()} row={getRow}/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {PsnView};
